package com.Ajava1704.for设计模式.for原型模式;

import java.io.*;
import java.util.Map;

/**
 * @类名: com.Ajava1704.for设计模式.for原型模式
 * @作者: lgt
 * @创建时间: 2020-02-15 14:46
 * @描述:深克隆,浅克隆
 **/
public class ForYuanXing implements Cloneable, Serializable {

    public ForYuanXing() {
        System.out.println("======构造方法====");
    }

    String username;
    String password;
    Map map;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Map getMap() {
        return map;
    }

    public void setMap(Map map) {
        this.map = map;
    }


    //浅克隆
    public ForYuanXing clone() throws CloneNotSupportedException {
        Object clone = super.clone();
        return (ForYuanXing) clone;
    }

    //深克隆
    public ForYuanXing deepClone() throws IOException, ClassNotFoundException {
        //序列化
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(this);

        //反序列化
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        ForYuanXing o = (ForYuanXing) objectInputStream.readObject();

        //关闭流
        objectInputStream.close();
        byteArrayInputStream.close();
        objectOutputStream.close();
        byteArrayOutputStream.close();

        return o;
    }
}
